package indi.simple.pms.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 类
 *
 * @author wanglunhui
 * @since 2022-04-13 16:38:11
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        RestTemplate restTemplate=new RestTemplate(factory);
        Iterator<HttpMessageConverter<?>> iterator=restTemplate.getMessageConverters().iterator();
        while (iterator.hasNext()){
            HttpMessageConverter<?> httpMessageConverter=iterator.next();
            if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter){
                MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter=((MappingJackson2HttpMessageConverter) httpMessageConverter);
                mappingJackson2HttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
                List<MediaType> mediaTypeList=new ArrayList<>(mappingJackson2HttpMessageConverter.getSupportedMediaTypes());
                mediaTypeList.add(MediaType.TEXT_HTML);
                mappingJackson2HttpMessageConverter.setSupportedMediaTypes(mediaTypeList);
            }
        }
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(10000);
        factory.setConnectTimeout(10000);
        // proxy
        return factory;
    }

}
